<template>
  <div class="TerminalAdministrate">
    <breadcrumb class="breadcrumb-container"></breadcrumb>
    <el-row>
      <el-form :model="Form" inline size="small">
        <el-button icon="el-icon-plus" size="small" type="primary" @click="handleGoToAddTerminal">终端入库</el-button>
        <el-button icon="el-icon-document" size="small" type="warning" @click="batch = true">批量入库</el-button>
        <el-form-item label="终端SN码">
          <el-select v-model="Form.sn" clearable filterable placeholder="请输入或选择">
            <el-option v-for="item in sn_list" :key="item.device_sn" :value="item.device_sn" :label="item.device_sn"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="终端类型">
          <el-select v-model="Form.category" placeholder="全部" clearable>
            <el-option v-for="item in categorys" :key="item.category" :value="item.category" :label="item.category_name"></el-option>
          </el-select>
        </el-form-item>
        <el-button icon="el-icon-search" size="small" type="success" @click="handleChangeSearch">设备查询</el-button>
      </el-form>
    </el-row>
    <el-row>
      <el-table :data="date" size="small" :header-cell-style="{background:'#f2f2f2'}">
        <el-table-column align="center" label="终端类型" prop="category"></el-table-column>
        <el-table-column align="center" label="终端名称" prop="device_id"></el-table-column>
        <el-table-column align="center" label="终端SN码" prop="device_sn"></el-table-column>
        <el-table-column align="center" label="绑定状态">
          <template slot-scope="scope">
            <span :class="scope.row.status === 0 ? 'err' : ''">{{ scope.row.status === 0 ? '未绑定' : scope.row.status === 1 ? '已绑定' : '不可用' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleClickList(scope.row.id)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="mt-10">
      <el-pagination class="fr" layout="total, prev, pager, next" :total="page.total" :page-size="page.size" :current-page.sync="page.current" @current-change="handleChangePage"></el-pagination>
    </el-row>
    <el-dialog :visible.sync="dialog" title="终端详情" width="400px">
      <p>终端编号：{{ dialog_item.sys_code }}</p>
      <p>终端类型：{{ dialog_item.category_name }}</p>
      <p>终端名称：{{ dialog_item.device_name }}</p>
      <p>终端SN码：{{ dialog_item.device_sn }}</p>
      <p>绑定状态：{{ dialog_item.status }}</p>
      <p v-if="dialog_item.category_name === '云打印'">客户云密码：{{ dialog_item.pwd }}</p>
      <p>所属代理商：{{ dialog_item.agent_name }}</p>
      <p>入库时间：{{ dialog_item.depot_create_at }}</p>
      <p>所属商户：{{ dialog_item.merchant_name }}</p>
      <p>所属门店：{{ dialog_item.store_name }}</p>
      <p>绑定时间：{{ dialog_item.create_at }}</p>
      <p>终端备注：{{ dialog_item.desc }}</p>
      <div slot="footer">
        <el-button v-if="dialog_item.status === '已绑定'" size="small" type="primary" @click="handleFileBinds">解除绑定</el-button>
        <el-button v-if="dialog_item.status === '未绑定'" size="small" type="danger" @click="handleDeleteTerminal">删除终端</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="batch" title="批量导入" width="400px">
      <el-form :model="File_list">
        <el-form-item style="padding-top:20px;margin-bottom:10px;">
          <span>导入文件模版下载</span>&nbsp;<el-button type="success" size="mini" @click="handleDloadExcel">下载模版</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;padding-bottom:30px;">
          <el-upload :action="url" :headers="headers" :data="agent" :on-success="handleUploadSuccess" :before-upload="handleUploadValid" :show-file-list="false" style="display:inline-block;">
            <el-input readonly placeholder="-请选择上传文件-" v-model="File_list.file" style="width:350px;"></el-input>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb'
import { TerminalAdminInit, TerminalConfigInit, TerminalConfigSnInit, TerminalAdminPage, TerminalAdminSearch, TerminalAdminList, TerminalAdminFileBind, TerminalAdminDelete } from '@/api/terminal'
import { mapGetters } from 'vuex'

export default {
  name: 'TerminalAdministrate',
  components: {
    Breadcrumb
  },
  data() {
    return {
      sn_list: [],
      categorys: [],
      date: [],
      dialog: false,
      batch: false,
      url: process.env.BASE_API + '/terminal/terminal/batch_warehousing',
      Form: {
        category: '',
        sn: ''
      },
      dialog_item: {
        id: '',
        sys_code: '',
        device_sn: '',
        status: '',
        pwd: '',
        device_name: '',
        category_name: '',
        create_at: '',
        store_name: '',
        merchant_name: '',
        agent_name: '',
        desc: '',
        depot_create_at: ''
      },
      File_list: {
        file: ''
      },
      page: {
        size: 0,
        current: 1,
        total: 0
      }
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token'
    ]),
    headers() {
      return {
        'user-auth-token': this.token,
        'user-id': this.id
      }
    },
    agent() {
      return {
        'agent_id': this.id
      }
    }
  },
  methods: {
    handleAdminInit() {
      TerminalAdminInit(this.id).then(res => {
        if (res.data.errorCode === 0) {
          this.date = res.data.result.depots.data
          this.page.size = res.data.result.depots.per_page
          this.page.current = res.data.result.depots.current_page
          this.page.total = res.data.result.depots.total
        } else {
          this.$message.error(res.data.errorMsg)
        }
      })
      TerminalConfigInit().then(res => {
        if (res.data.errorCode === 0) {
          this.categorys = res.data.result.category
        } else {
          this.$message.error(res.data.errorMsg)
        }
      })
      TerminalConfigSnInit(this.id).then(res => {
        if (res.data.errorCode === 0) {
          this.sn_list = res.data.result
        } else {
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    handleChangePage(v) {
      TerminalAdminPage(this.id, this.Form, v).then(res => {
        if (res.data.errorCode === 0) {
          this.date = res.data.result.depots.data
          this.page.size = res.data.result.depots.per_page
          this.page.current = res.data.result.depots.current_page
          this.page.total = res.data.result.depots.total
        } else {
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    handleChangeSearch() {
      TerminalAdminSearch(this.id, this.Form).then(res => {
        if (res.data.errorCode === 0) {
          this.date = res.data.result.depots.data
          this.page.size = res.data.result.depots.per_page
          this.page.current = res.data.result.depots.current_page
          this.page.total = res.data.result.depots.total
        } else {
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    handleClickList(id) {
      TerminalAdminList(id).then(res => {
        if (res.data.errorCode === 0) {
          this.dialog_item.depot_create_at = res.data.result.depot_create_at
          this.dialog_item.desc = res.data.result.desc
          this.dialog_item.agent_name = res.data.result.agent_name
          this.dialog_item.merchant_name = res.data.result.merchant_name
          this.dialog_item.store_name = res.data.result.store_name
          this.dialog_item.create_at = res.data.result.create_at
          this.dialog_item.category_name = res.data.result.category_name
          this.dialog_item.device_name = res.data.result.device_name
          this.dialog_item.pwd = res.data.result.pwd
          this.dialog_item.status = res.data.result.status
          this.dialog_item.device_sn = res.data.result.device_sn
          this.dialog_item.sys_code = res.data.result.sys_code
          this.dialog_item.id = res.data.result.id
          this.dialog = true
        } else {
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    handleFileBinds() {
      const h = this.$createElement
      this.$msgbox({
        title: '解除终端',
        message: h('p', null, '终端解绑后将无法正常使用终端功能，你是否确定解除' + this.dialog_item.category_name + this.dialog_item.device_sn + '？'),
        showCancelButton: true,
        confirmButtonText: '决意解绑',
        cancelButtonText: '再考虑一下',
        cancelButtonClass: 'el-button--info',
        confirmButtonClass: 'el-button--danger'
      }).then(() => {
        TerminalAdminFileBind(this.dialog_item.id).then(res => {
          if (res.data.errorCode === 0) {
            this.$message.success(res.data.errorMsg)
            TerminalAdminPage(this.id, this.Form, this.page.current).then(res => {
              if (res.data.errorCode === 0) {
                this.date = res.data.result.depots.data
                this.page.size = res.data.result.depots.per_page
                this.page.current = res.data.result.depots.current_page
                this.page.total = res.data.result.depots.total
              } else {
                this.$message.error(res.data.errorMsg)
              }
            })
            this.dialog = false
          } else {
            this.$message.error(res.data.errorMsg)
          }
        })
      }).catch(() => {})
    },
    handleDeleteTerminal() {
      const h = this.$createElement
      this.$msgbox({
        title: '删除终端',
        message: h('p', null, '删除终端后将无法正常使用终端功能，你是否确定删除' + this.dialog_item.category_name + this.dialog_item.device_sn + '？'),
        showCancelButton: true,
        confirmButtonText: '决意删除',
        cancelButtonText: '再考虑一下',
        cancelButtonClass: 'el-button--info',
        confirmButtonClass: 'el-button--danger'
      }).then(() => {
        TerminalAdminDelete(this.dialog_item.id).then(res => {
          if (res.data.errorCode === 0) {
            this.$message.success(res.data.errorMsg)
            TerminalAdminPage(this.id, this.Form, this.page.current).then(res => {
              if (res.data.errorCode === 0) {
                this.date = res.data.result.depots.data
                this.page.size = res.data.result.depots.per_page
                this.page.current = res.data.result.depots.current_page
                this.page.total = res.data.result.depots.total
              } else {
                this.$message.error(res.data.errorMsg)
              }
            })
            this.dialog = false
          } else {
            this.$message.error(res.data.errorMsg)
          }
        })
      }).catch(() => {})
    },
    handleGoToAddTerminal() {
      this.$router.push({ name: 'TerminalStorage' })
    },
    handleUploadSuccess(res) {
      if (res.errorCode === 0) {
        this.batch = false
        const h = this.$createElement
        this.$msgbox({
          title: '批量入库详情',
          showConfirmButton: false,
          showCancelButton: false,
          message: h('div', null, [
            h('p', null, '入库成功：' + res.result.success_count),
            h('p', null, '入库失败：' + res.result.error_count),
            h('p', null, '入库失败SN：' + res.result.error_sn.toString())
          ])
        }).then(() => {
        }).catch(() => {})
      } else {
        this.$message.error(res.errorMsg)
      }
    },
    handleUploadValid(file) {
      console.log(file)
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.error('上传文件只能是xlsx或xls格式哦~')
      }
      return isExcel
    },
    handleDloadExcel() {
      window.location.href = process.env.MAT_HOST + '/material/terminal_import_template.xls'
    }
  },
  created() {
    this.handleAdminInit()
  }
}
</script>